package util;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import json.Json_Account;
import json.Json_Company;
import json.Json_ManageModel;
import json.Json_Verify;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONStringer;

import com.google.gson.Gson;

public class Utils {
	private static final String TAG = "Utils\t\t";
	private static final String URL = _Config.URL;

	private static final String ENCODE_FORMAT = "UTF-8";

	private static final int TIME_OUT = 5 * 1000;
	public static final int HTTP_POST_TIME_OUT = 5 * 1000;	
	public static final int HTTP_CLIENT_TIME_OUT =  5 * 1000;
	
	private static final int CLIENT_BUFFER_SIZE = 8192;

	//*********************************************************************************************
	private static String getContent(String url) throws Exception {
		url = URL + url;
		StringBuilder sb = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		HttpParams httpParams = client.getParams();

		LogUtil.d(TAG, "url:" + url);
		
		HttpConnectionParams.setConnectionTimeout(httpParams, TIME_OUT);	// 设置网络超时参数
		HttpConnectionParams.setSoTimeout(httpParams, TIME_OUT);
		HttpResponse response = client.execute(new HttpPost(url));
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					entity.getContent(), "UTF-8"), CLIENT_BUFFER_SIZE);
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			reader.close();
		}
		
		String result = sb.toString();
		LogUtil.d(TAG, "getContent():" + result);
		
		return result;		
	}

	public static Object miLogin2(String loginname, String password) {
		
		Json_Account ac = null;
		try {
			String path2 = URL + "/member.action?act=login";
			String key = "subgson";
			
			String sss = getLoginModel(loginname, password);
			HttpClient httpClient = new DefaultHttpClient();   
			HttpPost httpPost = new HttpPost(path2);   
			
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair(key, sss));
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));   
			
			StringBuffer sb = new StringBuffer();  
			HttpResponse response = httpClient.execute(httpPost); 
			
			if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){   
			    HttpEntity entity = response.getEntity();   
			    if(entity!=null){   
			        BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));   
			        String line = null;   
			        while((line=reader.readLine())!=null){   
			            sb.append(line + "\n");   
			        }   
			        reader.close();   
			        String result = sb.toString();
			        LogUtil.e(TAG, result);
			        if(result==null)
			        	return null;
			        
			        ac = new Gson().fromJson(result, Json_Account.class);
					return ac;
			    }
			}
        	return null;
		} catch (Exception e) {
			if(_Config.DEBUG)e.printStackTrace();
			return null;
		}
	}
	public static String getLoginModel(String loginname, String password) {
		Json_ManageModel m = new Json_ManageModel();
		
		m.getAccount().setLoginname(loginname);
		m.getAccount().setPassword(password);

		long l = System.currentTimeMillis();			
		SimpleDateFormat sdf = new SimpleDateFormat("",Locale.SIMPLIFIED_CHINESE); 
		
		sdf.applyPattern("yyyy-MM-dd"); 			
		String timeStr = sdf.format(l); 
		
		System.out.println(timeStr);			
		m.getVerify().setTime(timeStr);
		
		Gson gx = new Gson();
		String sss = gx.toJson(m);

		LogUtil.e(TAG, sss);
		return sss;
	}

	public static Json_Company getMyCompany(Json_Account ac) {
		String path = "manage.action?module=company&act=getmodel";

		String returnStr = miManage(ac, path, null);
		LogUtil.d(TAG,  returnStr);

		Json_Company company = null;
		try{			
			Gson g = new Gson();
			company = g.fromJson(returnStr, Json_Company.class);
		
			long company_id = company.getId();
			String company_name = company.getCompanyName();
			
			LogUtil.d(TAG,  company_name);
			LogUtil.d(TAG,  Long.toString (company_id));

		}catch(Exception e){
			e.printStackTrace();
			return company;
		}
		return company;
	}
	/**
	 * 新增提交
	 * 
	 * @author 刘施洁
	 * @2011-12-29下午01:42:38
	 * @param path
	 *            提交路径
	 * @param str
	 *            提交模型
	 */

	//*********************************************************************************************
	private static String miManage(Json_Account ac, String path, String model) {
		String result = "";
		try {
			String path2 = URL + path;
			String str2 = preparbox(ac, model);
			
			LogUtil.d(TAG, "path:\t"+ path2);
			LogUtil.d(TAG,  "module:\t" + str2);

			String key = "subgson";
			HttpClient httpClient = new DefaultHttpClient();   
			HttpPost httpPost = new HttpPost(path2);   
			
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair(key, str2));
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));   
			
			StringBuffer sb = new StringBuffer();  
			HttpResponse response = httpClient.execute(httpPost);
			
			if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){   
			    HttpEntity entity = response.getEntity();   
			    if(entity!=null){   
			        BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));   
			        String line = null;   
			        while((line=reader.readLine())!=null){   
			            sb.append(line + "\n");   
			        }   
			        reader.close();   
			        LogUtil.e(TAG, sb.toString());
			        result = sb.toString();
			        return result;
			    }
			}
			return "";
			
		} catch (Exception e) {
			LogUtil.d(TAG,  "exception catched at miManage");
			e.printStackTrace();
			return "";
		}
	}
	/**
	 * 封装json包
	 * 
	 * @author 刘施洁
	 * @2012-1-6上午08:58:44
	 * @param a
	 * @param s
	 * @return
	 */
	//*********************************************************************************************
	public static String preparbox(Json_Account account, String arg_model) {
//		LogUtil.d(TAG,  "最后:"+new Gson().toJson(ac));
		try{			
			Json_ManageModel model = new Json_ManageModel();
			
			model.setAccount(account);
			model.setModel(arg_model);
	
			Json_Verify verify = new Json_Verify();
			verify.setTime(new Date().toString());
			verify.setPermit("123");// 设置定义好的干扰字符
	
			model.setVerify(verify);
			
			
			JSONStringer jsonText = new JSONStringer();
			jsonText.object(); 
			
		    jsonText.key("name");   
		    jsonText.value("yuanzhifei89");  
		    
		    LogUtil.e(TAG, "jsonText.toString():"+jsonText.toString());
		    
			String tmpstr = new Gson().toJson(model);
			model.getVerify().setPermit(MD5(tmpstr));// 使用md5加密后替换原来的干扰字符
	
			String str = new Gson().toJson(model);// 加入json
			return str;
		} catch (Exception e){
			e.printStackTrace();
			return "";
		}
	}

	//*********************************************************************************************
	/**
	 * MD5加密
	 * 
	 * @author 刘施洁
	 * @2012-1-6上午09:02:37
	 * @param sStr
	 * @return
	 */
	public static String MD5(String sStr) {
		String sReturnCode = "";
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(sStr.getBytes(ENCODE_FORMAT));
			byte b[] = md.digest();
			int i;
			StringBuffer sb = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0) {
					i += 256;
				}
				if (i < 16) {
					sb.append("0");
				}
				sb.append(Integer.toHexString(i));
			}

			sReturnCode = sb.toString();
		} catch (Exception ex) {

		}
		return sReturnCode;
	}
}
